package com.kun.base.net

import com.kun.base.BuildConfig
import com.kun.base.util.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * @author ZGL on 2018/5/22
 * retrofit日志拦截器
 */
class LoggingInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val t1 = System.nanoTime()
        val response = chain.proceed(request)
        val responseBody = response.body()
        val responseBodyString = response.body()!!.string()
        val newResponse = response.newBuilder().body(
            ResponseBody.create(
                responseBody!!.contentType(),
                responseBodyString.toByteArray()
            )
        ).build()
        if (BuildConfig.DEBUG) {
            val t2 = System.nanoTime()
            val sb = StringBuffer()
            sb.append(
                """
    -
    ---------- start ----------
    请求数据: ${response.request().url()}
    """.trimIndent()
            )
                .append("\n\n")
                .append("返回数据: $responseBodyString")
                .append("\n\n")
                .append(
                    """
    耗时: ${(t2 - t1) / 1e6}毫秒 ${request.url()}
    ---------- end ----------

    """.trimIndent()
                )
            LogUtils.i(sb.toString())
        }
        return newResponse
    }
}